<script setup>
import { ref } from 'vue';
import { useUploadStore } from '@/stores/upload';
import {createBatch, createBatchAndGetReport, getReport, uploadToOss} from "@/api/uploadRecord.js";
import {ElMessage} from "element-plus";
import {useTokenStore} from "@/stores/token.js";

const uploadStore = useUploadStore();
const selectedImage = ref(null);
const isModalOpen = ref(false);
const isLoading = ref(false); // 添加加载状态

// 上传处理
const handleFileUpload = async (event) => {
  const files = event.target.files;
  if (!files) return;

  try {
    // 上传图片到阿里云
    const response = await uploadToOss(Array.from(files));
    console.log("响应数据:", response.data);
    const urlList = response.data;

    for (let i = 0; i < urlList.length; i++) {
      const file = files[i];
      if (file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = (e) => {
          uploadStore.uploadedImages.push({
            id: Date.now() + i,
            url: urlList[i], // 使用URL数组中的对应项
            name: file.name,
            size: (file.size / 1024).toFixed(2) + 'KB',
          });
        };
        reader.readAsDataURL(file);
      }
    }
  } catch (error) {
    ElMessage.error('上传失败: ' + (error.message || '未知错误'));
    console.error(error);
  }
};

// 提交处理
const submitImages = async () => {
  if (uploadStore.uploadedImages.length === 0) {
    uploadStore.setResponse('请先上传图片');
    return;
  }

  isLoading.value = true;
  try {
    // 提取文件对象
    const imageUrls = uploadStore.uploadedImages.map(img => img.url);

    // 调用API
    const response = await createBatch(null,imageUrls);
    // 检查批次信息
    const taskBatch = response.data.taskBatch;
    let responseMessage = '图片处理成功！\n';
    responseMessage += '批次ID: ' + taskBatch.id + '\n';
    // 添加详细的批次信息
    if (taskBatch.totalDefects !== null && taskBatch.totalDefects !== undefined) {
      responseMessage += '总缺陷数: ' + taskBatch.totalDefects + '\n';
    }
    if (taskBatch.qualityScore !== null && taskBatch.qualityScore !== undefined) {
      responseMessage += '质量评分: ' + taskBatch.qualityScore.toFixed(2) + '\n';
    }
    if (taskBatch.qualityGradeDistribution) {
      responseMessage += '质量等级分布: ' + taskBatch.qualityGradeDistribution + '\n';
    }
    if (taskBatch.riskLevelDistribution) {
      responseMessage += '风险等级分布: ' + taskBatch.riskLevelDistribution + '\n';
    }
    if (taskBatch.successfulAnalyses !== null && taskBatch.successfulAnalyses !== undefined) {
      responseMessage += '成功分析数: ' + taskBatch.successfulAnalyses + '\n';
    }
    responseMessage += '\n详细信息生成中，如果报告详情页面未显示请等待一段时间然后刷新页面';
    uploadStore.setResponse(responseMessage);

    // 这里触发报告生成
    const tokenStore = useTokenStore();
    await getReport(response.data.taskBatch.id, tokenStore.token);
    // const response = await createBatchAndGetReport(null,imageUrls);
    // uploadStore.setResponse('图片处理成功！批次ID: '+response.data.taskBatch.id + '\n' + response.data.taskBatch.batchSummary);
  } catch (error) {
    console.error('提交错误:', error);
    uploadStore.setResponse('提交失败: ' + (error.response?.data?.message || error.message));
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="upload-container">
    <h1>{{ $t("system") }}</h1>

    <div class="upload-area">
      <label for="file-upload" class="upload-box">
        <div class="upload-icon">
          <svg viewBox="0 0 24 24" width="48" height="48">
            <path fill="currentColor" d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" />
          </svg>
        </div>
        <div class="upload-text">
          <p>{{ $t("upload-tip1") }}</p>
          <p class="hint">{{ $t("upload-tip2") }}</p>
        </div>
        <input
          id="file-upload"
          type="file"
          multiple
          accept="image/*"
          @change="handleFileUpload"
          class="file-input"
        >
      </label>
    </div>

    <!-- 图片预览区域 -->
    <div v-if="uploadStore.uploadedImages.length > 0" class="preview-section">
      <h2>{{ $t("upload-tip3") }} ({{ uploadStore.uploadedImages.length }}/10)</h2>
      <div class="image-grid">
        <div 
          v-for="image in uploadStore.uploadedImages" 
          :key="image.id" 
          class="image-item"
          @click="selectedImage = image; isModalOpen = true"
        >
          <img :src="image.url" :alt="image.name" class="thumbnail">
          <div class="image-info">
            <span class="image-name">{{ image.name }}</span>
            <span class="image-size">{{ image.size }}</span>
          </div>
          <button class="delete-btn" @click.stop="uploadStore.removeImage(image.id)">
            ×
          </button>
        </div>
      </div>
      
      <div class="action-buttons">
        <button
            class="submit-btn"
            @click="submitImages"
            :disabled="isLoading || uploadStore.uploadedImages.length === 0"
        >
          {{ isLoading ? "处理中..." : $t("upload-tip4") }}
        </button>
      </div>
    </div>

    <!-- 空间占位元素 -->
    <div class="useless" v-else></div>
    
    <!-- 后端响应区域 -->
    <div v-if="uploadStore.backendResponse" class="response-section">
      <h2>{{ $t("upload-tip5") }}</h2>
      <textarea 
        class="response-textarea" 
        readonly 
        v-model="uploadStore.backendResponse"
        :placeholder="$t('upload-tip7')"
      ></textarea>
      
      <div class="button-area">
        <button class="create-btn" @click="uploadStore.clear()">
          {{ $t("upload-tip8") }}
        </button>
      </div>

    </div>

    <!-- 图片放大模态框 -->
    <div v-if="isModalOpen" class="image-modal" @click.self="isModalOpen = false">
      <div class="modal-content">
        <button class="close-modal" @click="isModalOpen = false">×</button>
        <img :src="selectedImage?.url" :alt="selectedImage?.name" class="enlarged-image">
        <div class="image-details">
          <p>{{ selectedImage?.name }}</p>
          <p>{{ selectedImage?.size }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.upload-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: var(--bgcolor);
  color: var(--txcolor);
}

h1 {
  text-align: center;
  margin-bottom: 2rem;
  color: var(--header-color);
}

h2 {
  margin: 1.5rem 0 1rem;
  color: var(--secondary-color);
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.5rem;
}

.upload-area {
  margin-bottom: 2rem;
}

.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed var(--accent-color);
  border-radius: 8px;
  padding: 3rem 2rem;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: var(--card-bg);
  position: relative;
}

.upload-box:hover {
  background-color: var(--highlight-bg);
  border-color: var(--button-hover-bg);
}

.upload-icon {
  color: var(--accent-color);
  margin-bottom: 1rem;
}

.upload-text {
  text-align: center;
}

.hint {
  font-size: 0.9rem;
  color: var(--secondary-text);
  margin-top: 0.5rem;
}

.file-input {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
  top: 0;
  left: 0;
}

.useless {
  width: 100%;
  height: 321px;
  background-color: var(--bgcolor);
}

.preview-section {
  margin-top: 2rem;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1.5rem;
  margin-top: 1rem;
}

.image-item {
  position: relative;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
  transition: transform 0.2s;
  cursor: pointer;
  background: var(--card-bg);
}

.image-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px var(--border-color);
}

.thumbnail {
  width: 100%;
  height: 150px;
  object-fit: cover;
  display: block;
}

.image-info {
  padding: 0.75rem;
  background: var(--input-bg);
}

.image-name {
  display: block;
  font-size: 0.9rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--txcolor);
}

.image-size {
  font-size: 0.8rem;
  color: var(--secondary-text);
}

.delete-btn {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background: var(--clr);
  color: var(--select-color);
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s;
}

.delete-btn:hover {
  background: var(--footer-color);
  transform: scale(1.1);
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin: 2rem 0;
}

.submit-btn {
  background-color: var(--button-bg);
  color: white;
  border: none;
  padding: 0.75rem 2rem;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.submit-btn:hover {
  background-color: var(--button-hover);
}

.response-section {
  margin-top: 2rem;
}

.response-textarea {
  width: 100%;
  min-height: 200px;
  padding: 1rem;
  border: 1px solid var(--input-border);
  border-radius: 6px;
  font-family: inherit;
  resize: vertical;
  background-color: var(--contact-bg);
  color: var(--txcolor);
}

.button-area {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
  flex-wrap: wrap;
}

.download-btn {
  margin-top: 1rem;
  background-color: var(--progress-color);
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.download-btn:hover {
  background-color: var(--button-hover-bg);
}

.create-btn {
  margin-top: 1rem;
  background-color: var(--button-bg);
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.create-btn:hover {
  background-color: var(--button-hover);
}

.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.enlarged-image {
  max-width: 100%;
  max-height: 80vh;
  display: block;
  margin: 0 auto;
  border-radius: 4px;
}

.image-details {
  color: var(--select-color);
  text-align: center;
  margin-top: 1rem;
}

.close-modal {
  position: absolute;
  top: -40px;
  right: 0;
  background: none;
  border: none;
  color: var(--select-color);
  font-size: 2rem;
  cursor: pointer;
  padding: 0.5rem;
}

@media (max-width: 768px) {
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  .upload-container {
    padding: 1rem;
  }
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>